package com.yami.shop.otherservice;


import com.google.gson.Gson;
import com.yami.shop.bean.app.dto.DeliveryDto;
import com.yami.shop.common.util.Json;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据快递单号查询快递位置
 */
@Service
public class DeliveryDetailsService {
    //调试页
    //https://api.kuaidi100.com/debug-tool/query/#debug
    //控制台
    //https://api.kuaidi100.com/manager/v2/query/overview
    //快递公司编码对照表
    //https://api.kuaidi100.com/document/5f0ffb5ebc8da837cbd8aefc
    //账号密码: ASXXXXXXXX4 asXXXXXXXX7

    private String customer="685D509B2";
    private String key="JfK";

    public String getDeliveryInfo(String com,String num){
        Map<String,String> param=new HashMap<>();
        param.put("com",com);
        param.put("num",num);
        param.put("resultv2","4");

        String param1 = new Gson().toJson(param);

        String sign = DigestUtils.md5DigestAsHex((param1+key+customer).getBytes()).toUpperCase();

        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "param="+param1+"&customer="+customer+"&sign="+sign);
        Request request = new Request.Builder()
                .url("http://poll.kuaidi100.com/poll/query.do")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String deliveryInfo = new DeliveryDetailsService().getDeliveryInfo("yuantong", "YT3596143820365");
        DeliveryDto deliveryDto = Json.parseObject(deliveryInfo, DeliveryDto.class);
        System.out.println(deliveryDto);
    }
}
